﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.IO.Packaging;

namespace TestPlanWordWriter.Common.Word
{
    public class OpcToFlatConverter
    {
        public static XDocument OpcToFlat(Stream packageStream)
        {
            using (Package package = Package.Open(packageStream))
            {
                XNamespace packageNS = "http://schemas.microsoft.com/office/2006/xmlPackage";

                XDeclaration declaration = new XDeclaration("1.0", "UTF-8", "yes");
                XDocument document = new XDocument(declaration, new XProcessingInstruction("mso-application", "progid=\"Word.Document\""),
                    new XElement(packageNS + "package",
                        new XAttribute(XNamespace.Xmlns + "pkg", packageNS.ToString()),
                            package.GetParts().Select(part => GetContentsAsXml(part))
                    )
                );
                return document;
            }
        }

        private static XElement GetContentsAsXml(PackagePart part)
        {
            XNamespace packageNs = "http://schemas.microsoft.com/office/2006/xmlPackage";

            using (Stream partStream = part.GetStream())
            {
                using (StreamReader partReader = new StreamReader(partStream))
                {
                    using (XmlReader partXmlReader = XmlReader.Create(partReader))
                    {
                        return
                            new XElement(packageNs + "part",
                            new XAttribute(packageNs + "name", part.Uri),
                            new XAttribute(packageNs + "contentType", part.ContentType),
                                new XElement(packageNs + "xmlData",
                                    XElement.Load(partXmlReader)
                            )
                        );
                    }
                }
            }
        }

    }
}
